/*
 * #%L
 * java model
 * %%
 * Copyright (C) 2009 - 2011 prefabware.com Stefan Isele
 * %%
 * All Rights Reserved.
 * This program is dual-licensed under the GNU General Public license
 * or a commercial license.
 * You may select to use one or the other of these licenses.
 * To obtain a commercial license please contact Stefan Isele at www.stefan-isele.de
 * Any modifications to this file must keep this entire header intact.
 * Redistribution, except as permitted by the selected license, is prohibited.
 * #L%
 */
package com.prefabware.jmodel;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.prefabware.commons.Condition;
import com.prefabware.commons.QualifiedName;
import com.prefabware.jmodel.reference.JReference;

public abstract class JTypeWithFields extends JType{

	private Map<String,JField>fieldMap;

	public JTypeWithFields(QualifiedName qn, JTypeDeclaration declaration) {
		super(qn, declaration);
		this.fieldMap=new LinkedHashMap<String, JField>();
	}

	public void add(JField field) {
		String key = field.getName();
		Condition.isTrue(!this.fieldMap.containsKey(key), String.format("cannot add field %s, a field with this name allready exists : %s",key,this.fieldMap.get(key)));
		//TODO this is dangerous because declaringType changes hashCode and equals !!
		field.getDeclaration().setDeclaringType(this);
		fieldMap.put(key, field);
	}

	public JField getField(String fieldName) {
		return fieldMap.get(fieldName);
	}
	public Collection<JField> getFields() {
		return Collections.unmodifiableCollection(fieldMap.values());
	}
	public List<JReference<?>> getReferences() {
		List<JReference<?>> references = new ArrayList<JReference<?>>();
		references.addAll(super.getReferences());
		for (JField field : getFields()) {
			references.addAll(field.getReferences());
		}
		return references;
	}
}
